/**
 * -*- coding:utf-8 -*-
 *
 * @time: 2025/11/4 16:30
 * @author:lhl
 * @编辑器: IntelliJ IDEA
 */
package com.ljs.Dao.Impl;

import com.ljs.Dao.UserDao;
import com.ljs.Dao.util.JDBCUtils;
import com.ljs.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        Connection connection = JDBCUtils.getConnection();
        String sql = "select id,username,password from user where username=? and password=?";
        PreparedStatement statement =null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2,password);
            resultSet = statement.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JDBCUtils.closeAll(resultSet,statement,connection);
        }
        return null;
    }

    @Override
    public User selectByUsername(String username) {
        Connection connection = JDBCUtils.getConnection();
        String sql = "select id,username,password from user where username=? ";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                User user = new User(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeAll(resultSet, statement, connection);
        }
        return null;
    }

    @Override
    public int insertUser(User user) {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into user values (null,?,?)";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, user.getUsername());
            statement.setString(2, user.getPassword());
            int i = statement.executeUpdate();
            if (i > 0) {
                return 1;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtils.closeAll(null, statement, connection);
        }
        return 0;
    }
}
